import { createRouter, createWebHistory } from 'vue-router'
import app from '@/stores/app'

const routes = [
  {
    path: '/backend',
    name: 'BackendLayout',
    component: () => import('@/views/backend/BackendLayout.vue'),
    redirect: '/backend/vblog/list',
    beforeEnter: (to, from, next) => {
      const isAuthenticated = app.value.token && app.value.token.access_token
      if (isAuthenticated) {
        next()
      } else {
        next({ name: 'LoginPage' })
      }
    },
    children: [
      {
        path: 'vblog/list',
        name: 'BackendBlogList',
        component: () => import('@/views/backend/vblog/ListPage.vue')
      },
      {
        path: 'vblog/edit',
        name: 'BackendBlogEdit',
        component: () => import('@/views/backend/vblog/EditPage.vue')
      },
      {
        path: 'comment/list',
        name: 'BackendCommentList',
        component: () => import('@/views/backend/comment/CommentPage.vue')
      },
      {
        path: 'tags/list',
        name: 'BackendTagList',
        component: () => import('@/views/backend/tag/ListPage.vue')
      }
    ]
  },
  {
    path: '/frontend',
    name: 'FrontendLayout',
    component: () => import('@/views/frontend/FrontendLayout.vue'),
    redirect: '/frontend/vblog/list',
    children: [
      {
        path: 'vblog/list',
        name: 'FrontendBlogList',
        component: () => import('../views/frontend/vblog/ListPage.vue')
      },
      {
        path: 'vblog/detail',
        name: 'FrontendBlogDetail',
        component: () => import('../views/frontend/vblog/DetailPage.vue')
      }
    ]
  },
  {
    path: '/login',
    name: 'LoginPage',
    component: () => import('@/views/login/LoginPage.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/common/NotFound.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

export default router
